   $(function() { 
	   var isActive="2";
	   if($("#status").val()=='0'){
	 	  isActive="0";
	   }
	   var  table = $('#table_role');
		 var form = $('#modal_new_role').serializeObject();
		table.dataTable({
					"processing" : true,
					// 开启服务器模式
					serverSide : true,
					"ajax" : {
						url : "/a/wxconf/points",
						data:{"isActive":isActive}// 列表查询
					},
					"autoWidth" : false,
					"columns" : [
						{   "width" : "10%",
			                "data": "cutImg",
			                "render": function(data, type, row, meta) {
			                    return "<img class='center-block' src='"+data+"' alt='' />"
			              }
			            },
							{
								"width" : "20%",
								"data" : "ipName",
							},
							{
								"width" : "10%",
								"data" : "proPrice",
								"render" : function(data, type, row, meta) {
									return row.proPrice/100;
									}
							},
							{
								"width" : "10%",
								"data" : "changeIntegral",
								/*
								 * "render" : function(data, type, row, meta) {
								 * return "--"; }
								 */
							},
							{
								"width" : "20%",
								 "render" : function(data, type, row, meta) {
									     if(row.status=="0"){
									    	return  "<button type=\"button\" class=\"btn green btn_open_pintuan\" >上架</button><button type=\"button\" class=\"btn blue btn_edit_pintuan\">修改</button><button type=\"button\" class=\"btn green btn_view_pintuan\" >预览</button><button type=\"button\" class=\"btn red btn_del_role\">删除</button>";
									     }
									     else if(row.status=="1"){
												return "<button type=\"button\" class=\"btn blue btn_close_pintuan\">下架</button><button type=\"button\" class=\"btn green  btn_view_pintuan \" >预览</button>";
											}else if(row.status=="2"){
												return "";
											}else{
												return	"<button type=\"button\" class=\"btn red btn_del_role\">删除</button>";
											}
									}        
							} ],
					"language" : {
						"lengthMenu" : "每页显示 _MENU_ 条记录",
						"emptyTable" : "暂无数据记录",
						"info" : "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
						"zeroRecords" : "没有搜索到匹配记录",
						"infoEmpty" : "",
						"infoFiltered" : "",
						"processing" : ""
					},
					"destroy" : true,
					"ordering": false, 
					"pageLength" : 5,
					"order" : [ [ 0, "desc" ] ],
					"columnDefs" : [ {
						"orderable" : false,
						"targets" : [ 0,1,2,3,4]
					} ],
					"dom" : "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>"
							+ "<t>" + "<'row'<'col-md-5'i><'col-md-7'>p>",
					"fnInitComplete" : function() {
					} ,  "fnInitComplete": function() {
				           
		            	 if (isActive == "2") {
		            	 	$('.nav-tabs li:eq(0) a').tab('show');
		            	 	
		            	 } else{
		            	 	$('.nav-tabs li:eq(1) a').tab('show');
		            	 	
		            	 }
		            	 
		            }
				});
	    getTokenMessageForUditor();
	    getTokenMessage1();
	    getTokenMessage2();
	    // 删除图片
	    $(".imgclose").click(function(){
	    	if($(".imgclose").length==1){
	    		alert("最后一个详情图，不能删除")
	    		return;
	    	}
	    	if($("#endimg")){
	    		$("#endimg").css("margin-top","0px");
	    	}
	    	$(this).parent().parent().remove();
	    })
	    	  $("#addImg").on('click',function(e){
		  var length=	$("[name='imgUrl']").length;
		  if(length<4){
			  $("[name='imgUrl']:last").parent().parent().after('	<div class="col-md-3"><a  href="javascript:void 0;"><img class="img-responsive img" name="imgUrl" /><span class="img-responsive imgclose"></span></a></div>')
		  }else if(length==4){
			  $("[name='imgUrl']:last").parent().parent().after('	<div class="col-md-3" style="margin-top: 20px;"><a  href="javascript:void 0;"><img class="img-responsive img" name="imgUrl" /><span class="img-responsive imgclose"></span></a></div>')
		  }else{
			  alert("详情图片最多可以添加5张");
			  return;
		  }
		  $(".imgclose").unbind('click');

		    $(".imgclose").click(function(){
		    	if($(".imgclose").length==1){
		    		alert("最后一个详情图，不能删除")
		    		return;
		    	}
		    	if($("#endimg")){
		    		$("#endimg").css("margin-top","0px");
		    	}
		    	$(this).parent().parent().remove();
		    //	imgcount--;
		    })
		     $("#sgDetail_add").prop("disabled",false)
	  })
	    // 拼团规格
	    var lm = $("input[name='ipType']:checked").parent("label").index();
		console.log(lm);
		$(".specCon").eq(lm).show();
		
		$(".ruleType label").click(function(){
			var ln = $(this).index();
			$(".specCon").eq(ln).show().siblings(".specCon").hide();
		});
		if($("input[name='ipType']:checked").val()=="2"){// 多规格
			var _id = $("input[name='id']").val();
			// 启用
			$.ajax({
				url : '/a/wxconf/point/getspecDetail',
				type : 'post',
				dataType : 'json',
				contentType : "application/json; charset=utf-8",
				data :JSON.stringify({id : _id}),
			}).done(function(data) {
				if (data.status === '1') {
					var st1 =	$("input[name='spType1']").val();
					var st2 =$("input[name='spType2']").val();
					var st3 =	$("input[name='spType3']").val();
					var specDetailsList = $("input[name='specDetails']").val();
					var list= JSON.parse($("input[name='list']").val());
					var trth = "<tr>";
					var count = 0;
					if(st1!=""){
						trth+='<th><input type="hidden"  name="specType1" value="'+st1+'" maxlength="8">'+st1+'</th>';
						count = count+1;
					}
					if(st2!=""){
						trth+='<th><input type="hidden"  name="specType2" value="'+st1+'" maxlength="8">'+st2+'</th>';
						count = count+1;
					}
					if(st3!=""){
						trth+='<th><input type="hidden"  name="specType3" value="'+st1+'" maxlength="8">'+st3+'</th>';
						count = count+1;
					}
					trth+="<th>售价（元）</th><th>兑换积分</th></tr>";
					var trtr = "<tr>";
					
					if(data.data!=null){
						var specDetails = data.data;
						for(var i =0; i<specDetails.length;i++){
							if(count == 1){
								trtr+='<td><input type="hidden"  name="specDetails1" value="'+specDetails[i].specDetails1+'" maxlength="8">'+specDetails[i].specDetails1+'</td>';
                              }else if(count==2){
                            	  trtr+='<td><input type="hidden"  name="specDetails1" value="'+specDetails[i].specDetails1+'" maxlength="8">'+specDetails[i].specDetails1+'</td>';
                            	  trtr+='<td><input type="hidden"  name="specDetails2" value="'+specDetails[i].specDetails2+'" maxlength="8">'+specDetails[i].specDetails2+'</td>';
							}else if(count==3){
								trtr+='<td><input type="hidden"  name="specDetails1" value="'+specDetails[i].specDetails1+'" maxlength="8">'+specDetails[i].specDetails1+'</td>';
								trtr+='<td><input type="hidden"  name="specDetails2" value="'+specDetails[i].specDetails2+'" maxlength="8">'+specDetails[i].specDetails2+'</td>';
								trtr+='<td><input type="hidden"  name="specDetails3" value="'+specDetails[i].specDetails3+'" maxlength="8">'+specDetails[i].specDetails3+'</td>';
							}
						/*	trtr+="<td>"+specDetails[i].specValue2/100+"</td>";
							trtr+="<td>"+specDetails[i].specValue1/100+"</td>";*/
							trtr+='<td><input type="text" class="form-control input-small" name="storeCount" value="'+specDetails[i].specValue1/100+'" maxlength="8"></td>';
							trtr+='<td><input type="text" class="form-control input-small" name="warnCount" min="1"  value="'+specDetails[i].specValue2+'" maxlength="8"></td></tr>';
						}
						if(st1!=""){
							$("#addSpecTypeBtn").trigger("click");
						}
						if(st2!=""){
							$("#addSpecTypeBtn").trigger("click");
						}
						if(st3!=""){
							$("#addSpecTypeBtn").trigger("click");
						}
					}
					$("#table_spec tbody").append(trth);
					$("#table_spec tbody:last").append(trtr);
					
                       $("#modify_spec input[name='specType']").each(function(m){
						$(this).val(list[m]["specType"]);
						var specDetails=list[m]["specDetails"];
						for(var j=0;j<specDetails.length;j++){
							$(this).next("span").find(".addSepcDetailBtn").trigger("click");
						}
						var arrayDtl=list[m]["specDetails"];
						$(this).parent().parent().parent().find("input[name='specDetails']").each(function(n){
							  $(this).val(arrayDtl[n].trim());
						})
					});
					
				} else if (data.status === '2') {
					alert(data.message);
				}
			});
		}
		
		var specmodifyList = "";
		$(".modifySpecDetailSure").on("click",function(e){
			$("#add_spec").modal("hide");
			//找到编辑的行
			 $("#table_spec1 tbody:last").find("tr").each(function(){
				
				 if(typeof($(this).attr("id"))!="undefined"){
					   if($(this).attr("id")=="tr_1"){ //替换当前行的值
						 //  alert($(this).next("tr").html());
						   $(this).find("td").eq(0).html($("#modify_spec input[name='specType']").val());
						   //添加label
							$("#form_spec_modify .spec_list_edit label").each(function(i){
								specmodifyList="<label >"+$("#form_spec_modify .spec_list_edit label").eq(i).text()+"</label>";
								specmodifyList=specmodifyList+"<label >"+$("#form_spec_modify .spec_list_edit label").eq(i).text()+"</label>";
							})
							$(this).next("tr").html(specmodifyList);
							//
							$("input[name='editSpec']").val("");
					   }
					   
				 }
			 });
		});
		// 编辑规格
		$("#modifySpecTypeAndDetail").click(function(){
// $(".btn_add").hide();
			$("#modify_spec").modal("show");
// $("input[name='specTypeName1']").val("");
		});
		
		//规格模版
		var specTypeTemplate = stringLines(function(){/*
			<div class="modal-footer">
				<div class="form-group">
					<lable class="col-md-3 control-label"><span class="required"> * </span>规格名称：
					</lable>
					<div class="col-md-9 input-group">
						<input type="text" class="form-control input-medium" name="specType" maxlength="10" placeholder="请输入规格名称">
						<span class="input-group-btn">									        		
			        		<button class="btn btn-info addSepcDetailBtn" type="button">添加规格值</button>
			        		<button class="btn btn-info delSelfBtn1" type="button">删除</button>
			    		</span>
					</div>											
				</div>
			</div>
		*/});
		//规格值模版
		var specDetailTemplate = stringLines(function(){/*
			<div class="form-group">
				<lable class="col-md-3 control-label"><span class="required"> * </span>规格值名称：
				</lable>											
				<div class="col-md-9 input-group">
					<input type="text" class="form-control input-medium" name="specDetails" maxlength="10" placeholder="请输入规格值名称">
					<span class="input-group-btn">
		        		<button class="btn btn-info delSelfBtn2" type="button">删除</button>									        		
		    		</span>
				</div>
			</div>
		*/});
		
		// 下架拼团
		table.on('click', '.btn_close_pintuan', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要下架?",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							var _data = JSON.stringify({
								id : _id,status:0
							});
							// 启用
							$.ajax({
								url : '/a/wxconf/point/pointEdit',
								type : 'post',
								dataType : 'json',
								contentType : "application/json; charset=utf-8",
								data : _data,
							}).done(function(data) {
								if (data.status === '1') {
									table.DataTable().ajax.reload();
								} else if (data.status === '2') {
									alert(data.message);
								}
							});
						}
					}
				}
			});
		});
		//删除
		table.on('click', '.btn_del_role', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要删除?",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							var _data = JSON.stringify({
								id : _id,status:2
							});
							// 删除
							$.ajax({
								url : '/a/wxconf/point/pointDel',
								type : 'delete',
								dataType : 'json',
								contentType : "application/json; charset=utf-8",
								data : _data,
							}).done(function(data) {
								if (data.status === '1') {
									table.DataTable().ajax.reload();
								} else if (data.status === '2') {
									alert(data.message);
								}
							});
						}
					}
				}
			});
		});
		
		// 启用拼团
		table.on('click', '.btn_open_pintuan', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要上架?",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							var _data = JSON.stringify({
								id : _id,status:1
							});
							// 启用
							$.ajax({
								url : '/a/wxconf/point/pointEdit',
								type : 'post',
								dataType : 'json',
								contentType : "application/json; charset=utf-8",
								data : _data,
							}).done(function(data) {
								if (data.status === '1') {
									table.DataTable().ajax.reload();
								} else if (data.status === '2') {
									alert(data.message);
								}
							});
						}
					}
				}
			});
		});
		
		// 添加规格类型
		$("#addSpecTypeBtn").click(function(){
			
			if($("#modify_spec form .addSepcDetailBtn").length<3){
				$("#modify_spec form > div:last").before(specTypeTemplate);
				
				// 添加规格
				$("#modify_spec form .addSepcDetailBtn:last").click(function(){
					var specDom = $(this).parent().parent().parent().parent();
					if(specDom.find(".delSelfBtn2").length<10){
						specDom.append(specDetailTemplate);
						$("#modify_spec form .delSelfBtn2").click(function(){					
							$(this).parent().parent().parent().remove();
						});
					}else{
						alert("最多10个");
					}					
				});
				
				$("#modify_spec form .delSelfBtn1:last").click(function(){				
					$(this).parent().parent().parent().parent().remove();
				});
			}else{
				alert("最多3个");
			}			
			
		});
		
		// 完成编辑规格
		$("#modifySpecDetailSure").click(function(){
			var newSpecMetaData = [];
			var isTrue="";
			var arry1 = [];
			var arry2 = [];
			var isRepeat="";
			$("#modify_spec input[name='specType']").each(function(m){
				if (!mdTool.validate($(this).val(), 'require')) {
					$(".modify_spec_help-block").html("请输入规格名称");
					$(".modify_spec_help-block").css("color",'red');
					if(!isTrue){isTrue="请输入规格名称";}
					return;
				}
				if(!newSpecMetaData[m]){
					newSpecMetaData[m] = {};
				}
				if(!arry1[m]){
					arry1[m] = {};
				}
				arry1[m]=$(this).val();
				newSpecMetaData[m]["specType"]=$(this).val();
				if($(this).parent().parent().parent().find("input[name='specDetails']").length==0){
					$(".modify_spec_help-block").html("缺少规格值名称，请添加规格值");
					$(".modify_spec_help-block").css("color",'red');
					if(!isTrue){
						isTrue="缺少规格值名称，请添加规格值";
					}
					return;
				}
				
				$(this).parent().parent().parent().find("input[name='specDetails']").each(function(n){
					if(!newSpecMetaData[m]["specDetails"]){
						newSpecMetaData[m]["specDetails"] = [];
					}
					newSpecMetaData[m]["specDetails"][n] = $(this).val();
					if (!mdTool.validate($(this).val(), 'require')) {
						$(".modify_spec_help-block").html("请输入规格值名称");
						$(".modify_spec_help-block").css("color",'red');
						if(!isTrue){
							isTrue="请输入规格值名称";
						}
						return;
					}
					if(!arry2[n]){
						arry2[n] = {};
					}
					arry2[n]=$(this).val();
					
					
				})
				if(mdTool.isRepeat(arry2)){
					if(!isRepeat){isRepeat="规格名称值相同，请修改";}
					$(".modify_spec_help-block").html("规格名称值相同，请修改");
					$(".modify_spec_help-block").css("color",'red');
					return false;
				}
				
			});
			if(isTrue){
				$(".modify_spec_help-block").html(isTrue);
				$(".modify_spec_help-block").css("color",'red');
				return;
			}else{
				$(".modify_spec_help-block").html("");
			}
			if(newSpecMetaData.length == 0){
				$(".modify_spec_help-block").html("请添加规格");
				$(".modify_spec_help-block").css("color",'red');
				return;
			}
			if(	$(this).parent().parent().parent().find("input[name='specDetails']").length<=0){
				$(".modify_spec_help-block").html("请添加规格值");
				$(".modify_spec_help-block").css("color",'red');
				return;
			}
			if(mdTool.isRepeat(arry1)){
				$(".modify_spec_help-block").html("规格名称相同，请修改");
				$(".modify_spec_help-block").css("color",'red');
				return;
			}
			if(isRepeat){
				$(".modify_spec_help-block").html("规格值名称相同，请修改");
				$(".modify_spec_help-block").css("color",'red');
				return;
			}else{
				$(".modify_spec_help-block").html("");
			}
			
			$("#modify_spec").modal("hide");
			// 生成规格组合表格
			if(newSpecMetaData.length > 0){
				var specHeadBuf = "<tr>";
				for(var i=0; i<newSpecMetaData.length; i++){
					//specHeadBuf += "<th>";
					specHeadBuf += '<th><input type="hidden" name="specType'+(Number(i)+1)+'" value="'+ newSpecMetaData[i]['specType']+'">';
					specHeadBuf += newSpecMetaData[i]["specType"];
					specHeadBuf += "</th>";
				}
				specHeadBuf += "<th>售价（元）</th><th>兑换积分</th>";
				specHeadBuf += "</tr>";
				
				var specBodyBuf = "";				
				// 生成行数据
				var specIds="";
				var buildBodyRowFunc = function(){
					var specRowBuf = "<tr>";
					for(var x in arguments){
						/*specRowBuf += "<td>";*/
						specRowBuf += '<td><input type="hidden" name="specDetails'+(Number(x)+1)+'" value="'+ arguments[x]+'">';
						specRowBuf += arguments[x];
						specRowBuf += "</td>";
						specIds+=specIds
					};
					specRowBuf += stringLines(function(){/*
						<td>
							<input type="text" class="form-control input-small" name="storeCount" maxlength="8">
							<input type="hidden" name="isStore" value="1">
						</td>
						<td>
							<input type="text" class="form-control input-small" name="warnCount" maxlength="8">
						</td>
						
					*/});
					specRowBuf += "</tr>";
					return specRowBuf;
				}
				for(var spec1 in newSpecMetaData[0]["specDetails"]){
					if(newSpecMetaData.length > 1){
						for(var spec2 in newSpecMetaData[1]["specDetails"]){
							if(newSpecMetaData.length == 3){
								for(var spec3 in newSpecMetaData[2]["specDetails"]){
									specBodyBuf += buildBodyRowFunc(newSpecMetaData[0]["specDetails"][spec1],
											newSpecMetaData[1]["specDetails"][spec2],
											newSpecMetaData[2]["specDetails"][spec3]);
								}
							}else{
								specBodyBuf += buildBodyRowFunc(newSpecMetaData[0]["specDetails"][spec1],
										newSpecMetaData[1]["specDetails"][spec2]);
							}
						}
					}else{
						specBodyBuf += buildBodyRowFunc(newSpecMetaData[0]["specDetails"][spec1]);
					}
				}
				
				// 将DOM写到页面
				$("#table_spec thead").html(specHeadBuf);
				$("#table_spec tbody").html(specBodyBuf);
				var _data = $("#modal_new_role").serializeObject();
				var specDetails1s=_data.specDetails1;
				var length;
				if(_data.specType3){
					length=3;
				}else
				if(_data.specType2){
					length=2;
				}else
				if(_data.specType1){
					length=1;
				}
			
				var specDetails2s=_data.specDetails2;
				var specDetails3s=_data.specDetails3;
				var storeCounts=_data.storeCount;
				var warnCounts=_data.warnCount;
				var limitCounts=_data.limitCount;
				var specValue1s=_data.specValue1;
				var specType1=$("#table_spec tbody tr:first").find("input[name='specType1']").val();
				var specType2=$("#table_spec tbody tr:first").find("input[name='specType2']").val();
				var specType3=$("#table_spec tbody tr:first").find("input[name='specType3']").val();


				$("#table_spec tbody").find("tr").each(function(i){
					var specDetails1=$(this).find("input[name='specDetails1']").val();
					var specDetails2=$(this).find("input[name='specDetails2']").val();
					var specDetails3=$(this).find("input[name='specDetails3']").val();
					
					for(var a in specDetails1s){
						if(length===1){
							if(specDetails1s[a]==specDetails1&&!specType2){
								$(this).find("input[name='storeCount']").val(storeCounts[a])
								$(this).find("input[name='warnCount']").val(warnCounts[a])
								$(this).find("input[name='limitCount']").val(limitCounts[a])
								$(this).find("input[name='specValue1']").val(specValue1s[a])
							}
						}if(length===2){
							if(specDetails1s[a]==specDetails1&&specDetails2s[a]==specDetails2&&!specType3){
								$(this).find("input[name='storeCount']").val(storeCounts[a])
								$(this).find("input[name='warnCount']").val(warnCounts[a])
								$(this).find("input[name='limitCount']").val(limitCounts[a])
								$(this).find("input[name='specValue1']").val(specValue1s[a])
							}
						}else if(length===3){
							if(specDetails1s[a]==specDetails1&&specDetails2s[a]==specDetails2&&specDetails3s[a]==specDetails3){
								$(this).find("input[name='storeCount']").val(storeCounts[a])
								$(this).find("input[name='warnCount']").val(warnCounts[a])
								$(this).find("input[name='limitCount']").val(limitCounts[a])
								$(this).find("input[name='specValue1']").val(specValue1s[a])
							 }
						}	
					}


					
				})
				
				$(".isStoreCheck").on("click",function(e){
					if($(this).is(':checked')) {
						$(this).parent().find("input[name='isStore']").val("1")
					}else{
						$(this).parent().find("input[name='isStore']").val("0")
					}

				})
				
			}
			
		});
		
		$(".addSpecDetail").on("click",function(e){
			var spec = $("#form_spec_new input[name='specDetails']").val();
			$("#form_spec_new .spec_list").append('<label >'+ spec +'<span class="glyphicon glyphicon-remove"></span></label>');

		})
		//修改规则
		$(".modifySpecDetail").on("click",function(e){
			var spec = $("#form_spec_modify input[name='specDetails']").val();
			$("#form_spec_modify .spec_list_edit").append('<label >'+ spec +'<span class="glyphicon glyphicon-remove"></span></label>');

		})
		
		
		$(".btn_add2 .btn_save_role").click(function(){
			$(".btn_add2").hide();
			$(".btn_add_con2").show();
			$(".spec_list2").hide();
			$("#sst").show();
			
		});
		
		table.on('click', '.btn_edit_pintuan', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
			.data(); // 操作行对象
	        var _id = oData_arr[0].id;
			window.location.href = "/p/wxconf/point/integralProEdit?id="
					+ encodeURIComponent(_id);
		});
		
		$("#add_spellGroup").on("click",function(){
			window.location.href = "/p/wxconf/point/integralPro";
			});
		$("#add_integralRule").on("click",function(){
			window.location.href = "/p/wxconf/point/integral";
			});
		$("#sel_inteOrder").on("click",function(){
			window.location.href = "/p/wxconf/point/integralOrder";
			});
		// 保存
		$("#save").click(function(){
			var _data = $("#modal_new_role").serializeObject();
		    var	specTypeArray = new Array();
		    var array = new Array();
		    var inteComb;
	 		if (!mdTool.validate(_data.sgName, 'require')) {
	 			mdTool.showMessage('请输入积分商品名称');
	 			return;
	 		}
	 		
			  if (!mdTool.validate($("img[name='img']")[0].src, 'require')) {
			  mdTool.showMessage('请上传积分商品图片'); return; } if
			  (!mdTool.validate($("img[name='imgUrl']")[0].src, 'require')) {
			 mdTool.showMessage('请上传积分商品详情图'); return; }
			 
	 		if($("input[name='ipType']:checked").parent().text().trim()=="统一规格"){
	 		/*
			 * if(!parseFloat($("input[name='sgPrice1']").val())>0.00){
			 * mdTool.showMessage('请输入大于0的拼团价'); return; }
			 */
	 		if (!mdTool.validate(_data.proPrice1, 'require')) {
	 			mdTool.showMessage('请输入售价');
	 			return;
	 		}
	 		if(_data.proPrice1.length>8){
	 			mdTool.showMessage('商品售价最多只能8位数！');
	 			return;
	 		}
	 		if (!mdTool.validate(_data.proPrice1, 'znum')) {
	 			mdTool.showMessage('请输入正数售价');
	 			return;
	 		}
	 		if (!mdTool.validate(_data.changeIntegral, 'num')) {
	 			mdTool.showMessage('请输入正整数商品兑换积分');
	 			return;
	 		}
	 		if($("input[name='changeIntegral']").val().length>8){
	 			mdTool.showMessage('请输入8位数以内的商品兑换积分');
	 			return;
	 		}
	 		}else{
	 			// var  specArray = _data.specType;
	 			  var specDetails1s= _data.specDetails1;
	 			 if(!specDetails1s){
	    	    		mdTool.showMessage('请输入商品规格');
	    	    		return;
			}
	 			if(specDetails1s instanceof Array){
	 		    	  var length=specDetails1s.length;
	 		    	     array=new Array(length);
	 		    	    for(var i=0;i<length;i++){
	 		    	    	if (!mdTool.validate(_data.storeCount[i], 'require')) {
	 		    	    		mdTool.showMessage('请输入商品售价');
	 		    	    		return;
	 		    	    	}
	 		    	    	if (!mdTool.validate(_data.warnCount[i], 'num')) {
	 		    	    		mdTool.showMessage('请输入正整数商品兑换积分');
	 		    	    		return;
	 		    	    	}
	 		    	    	if(_data.warnCount[i].length>8){
	 		   	 			mdTool.showMessage('请输入8位数以内的商品兑换积分');
	 		   	 			return;
	 		   	 			}
	 		    	    	
 		    	    		if(_data.specDetails3){
 		    	    			var IntegralsComb={"specDetails1":_data.specDetails1[i],"specDetails2":_data.specDetails2[i],"specDetails3":_data.specDetails3[i],"specValue1str":_data.storeCount[i],"specValue2":_data.warnCount[i]};
 		 		    	    	array[i]=IntegralsComb;
 		    	    		}else if(_data.specDetails2){
 		    	    			var IntegralsComb={"specDetails1":_data.specDetails1[i],"specDetails2":_data.specDetails2[i],"specValue1str":_data.storeCount[i],"specValue2":_data.warnCount[i]};
 		 		    	    	array[i]=IntegralsComb;
 		    	    		}else{
 		    	    			var IntegralsComb={"specDetails1":_data.specDetails1[i],"specValue1str":_data.storeCount[i],"specValue2":_data.warnCount[i]};
 		 		    	    	array[i]=IntegralsComb;
 		    	    		}
	 		    	    }
	 		    }else{
	 		    	if (!mdTool.validate(_data.storeCount, 'require')) {
		    	    		mdTool.showMessage('请输入商品售价');
		    	    		return;
		    	    	}
		    	    	if (!mdTool.validate(_data.warnCount, 'num')) {
		    	    		mdTool.showMessage('请输入正整数商品兑换积分');
		    	    		return;
		    	    	}
		    	    	if(_data.warnCount.length>8){
	 		   	 			mdTool.showMessage('请输入8位数以内的商品兑换积分');
	 		   	 			return;
	 		   	 		}
	 		    	
		    	    		if(_data.specDetails3){
		    	    			var IntegralsComb={"specDetails1":_data.specDetails1,"specDetails2":_data.specDetails2,"specDetails3":_data.specDetails3,"specValue1str":_data.storeCount,"specValue2":_data.warnCount};
		    	    			inteComb=IntegralsComb;
		    	    		}else if(_data.specDetails2){
		    	    			var IntegralsComb={"specDetails1":_data.specDetails1,"specDetails2":_data.specDetails2,"specValue1str":_data.storeCount,"specValue2":_data.warnCount};
		    	    			inteComb=IntegralsComb;
		    	    		}else{
		    	    			var IntegralsComb={"specDetails1":_data.specDetails1,"specValue1str":_data.storeCount,"specValue2":_data.warnCount};
		    	    			inteComb=IntegralsComb;
		    	    		}
	 		    }
	 		}
	 		if (mdTool.validate(_data.sort, 'require')) {
	 			if (!mdTool.validate(_data.sort, 'num')) {
	 				mdTool.showMessage('请输入正整数排序');
	 	    		return;
	 			}
 	    	}
	 		
	 		if(UM.getEditor('container').getContent().length=="0"){
			mdTool.showMessage('请输入积分商品详情');
 			return;
		   };
			if(UM.getEditor('container').getContent().length>=20000){
				$("#gg").css("color","red");
				return;
			};
						
			// 循环多个详情图片
			var imgUrls = "";
			$("img[name='imgUrl']").each(function(){
				imgUrls += $(this).attr("src")+","
			})
			var specType = "1";
			var param = "";
			if($("input[name='ipType']:checked").parent().text().trim()=="统一规格"){
				 param = {"IntegralProducts":{"id":_data.id,"ipName":_data.sgName,"img":$("img[name='img']")[0].src,"cutImg":$("img[name='cutImg']")[0].src,
					"ipType":specType,"sort":_data.sort,"ipDetails":_data.sgdetails,"changeIntegral":_data.changeIntegral,"proPrice":_data.proPrice1},
		            	"IntegralsProductImg":{ "imgUrl":imgUrls}};
			}else if($("input[name='ipType']:checked").parent().text().trim()=="多规格"){
				specType = "2";
				var st1 = $("input[name='specType1']").parent("th").text();
				var st2 = $("input[name='specType2']").parent("th").text();
				var st3 = $("input[name='specType3']").parent("th").text();
				 param = {"IntegralProducts":{"id":_data.id,"ipName":_data.sgName,"img":$("img[name='img']")[0].src,"cutImg":$("img[name='cutImg']")[0].src,
						"ipType":specType,"specType1":st1,"specType2":st2,"specType3":st3,"sort":_data.sort,"ipDetails":_data.sgdetails},"IntegralsProductImg":{ "imgUrl":imgUrls},
			            	"IntegralsComb":inteComb,"IntegralsCombs":JSON.stringify(array)};
			}
			// alert(JSON.stringify(param));
			var urls = "/a/wxconf/point/addIntegralPro";
			var types= "put";
			if (_data.id) {
				types = "post";
				urls = "/a/wxconf/point/editIntegralPro";
			}
			$.ajax({
                url:urls,
                type: types,
                async: false,// 这里应设置为同步的方式
                data: JSON.stringify(param),
                dataType : 'json',
                contentType : "application/json; charset=utf-8",
                success: function (data) {
                	if(data.status=='1'){
                		// 跳转到列表页面
                		//window.location.href = "/p/wxconf/point/integralList";
                		window.location.href = "/p/wxconf/point/edit?status=0";

                		}else{
                			$('#modal_new_role .help-block').html(data.message); // 返回错误信息
							$("#modal_new_role .help-block").attr("style","color:red;");
                	}
                }
            });
			
		});
		
		$(".btn_add_con2 .btn_cancle_role").click(function(){
			$(".btn_add2").show();
			$(".btn_add_con2").hide();
		});
		
		$(".btn_add_con2 .btn_save_role").click(function(){
			// 获取选中的规格，没选提示它
			$("#selst").html($("#selectSpecType").val());
			// $(".btn_add2").show();
			$(".spec_list2").show();
			$(".spec_list2 label").hide();
			$(".spec_list2 #selst").show();
			$("#sst").hide();
			// 隐藏保存和取消
			$(".btn_add_con2 .btn").hide();
		});
		
		$("#selst").click(function(){
			$(".btn_add2").hide();
			$(".btn_add_con2").show();
			$("#sst").show();
			$(".spec_list2").hide();
			$(".btn_add_con2 .btn").show();
			$("#selst").html("");
		});
		
		 $("#table_spec #tb1").on('click','.btn_cancle_spec',function(){
				$(this).parent().parent().remove();
			});
		 // 预览
		 table.on('click','.btn_view_pintuan',function(){
			 var oData_arr = table.DataTable().rows($(this).parents("tr"))
				.data(); // 操作行对象
		var _id = oData_arr[0].id;
    	window.open("/p/wxconf/point/viewintegralPro?id="+encodeURIComponent(_id),'top');

			});
		 
		 $('#btn_cancle').click(function(event) {
	        	window.history.back(); 
	        });
		 
		 
	});
   
	 var i = 0;
	 function addRow(){
		 if($("#selst").html()==""){
			 alert("请先选择规格!");
			 return;
		 }
	 	var str = '<tr class="addspec tr_' + i + '">'
	 	+'<td><input type="text" class="form-control" name="specValue"  maxlength = "12" /></td>'
	 	+'<td><input type="text" class="form-control" name="sgPrice" maxlength = "8" /></td>'
	 	+'<td><input type="text" class="form-control"  name="proPrice" maxlength = "8"></td>'
	 	+'<td><button type="button" class="btn btn_cancle_spec">取消</button></td>'
	 	+'</tr>';
	 	 $("#table_spec #tb1:last").append(str);
	 	 // getTokenMessage();
	 	    i++
	 };
	 
	  function dochang(num){
		 // alert(num);
		  var param={"status":num};
		  
		  $('#table_role').DataTable().search(JSON.stringify(param)).draw();
	};
	  
	  /*
		 * 页面加载完毕 发起请求获取七牛token，通过前台传到七牛
		 */

	  // 添加主图
	  function img_add(){
	  	getTokenMessage1();
	  }
	  // 添加详情图
	  function sgDetail_add(){
	  	getTokenMessage2();
	  }
	  function getTokenMessage1() {
	  	var url="";
	  	var qiniupercent="";
	  	var uploader="btn-uploader";
	  	var pickfiles="sgimg_add";
	  	$.ajax({
	  		url: '/a/qiniu/uptoken',
	  		type: 'POST',
	  		data: {},
	  		cache: false,
	  		contentType: false,    // 不可缺
	  		processData: false,    // 不可缺
	  		dataType : 'json',
	  		success: function (data) {
	  			var obj = data;
	  			uploaderReady(obj.uptoken,url,qiniupercent,uploader,pickfiles);
	  		  }
	  		});
	  };

	  function getTokenMessage2() {
	  	var url="";
	  	var qiniupercent="";
	  	var uploader="btn-uploader";
	  	var pickfiles="sgDetail_add";
	  	$.ajax({
	  		url: '/a/qiniu/uptoken',
	  		type: 'POST',
	  		data: {},
	  		cache: false,
	  		contentType: false,    // 不可缺
	  		processData: false,    // 不可缺
	  		dataType : 'json',
	  		success: function (data) {
	  			var obj = data;
	  			uploaderReady(obj.uptoken,url,qiniupercent,uploader,pickfiles);
	  		  }
	  		});
	  }

	  /**
		 * Created by lzw on 2017/09/16 . 七牛上传图片JS 传入token后执行方法
		 */

	  function uploaderReady(token,url,qiniupercent,uploader,pickfiles){
	      var uploader = Qiniu.uploader({
	          runtimes: 'html5,flash,html4',
	          browse_button: pickfiles,     // 上传按钮的ID
	          container: uploader,      // 上传按钮的上级元素ID
	          drop_element: uploader,
	          max_file_size: '100mb',         // 最大文件限制
	          flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
	          dragdrop: false,
	          chunk_size: '4mb',              // 分块大小
	          // uptoken_url: '', //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
	          uptoken: token,                 // 若未指定uptoken_url,则必须指定 uptoken
												// ,uptoken由其他程序生成
	          // save_key: true, // 默认 false。若在服务端生成uptoken的上传策略中指定了
				// `sava_key`，则开启，SDK在前端将不对key进行任何处理
	          domain: qiniuConfig.returnUrl(),   // 自己的七牛云存储空间域名
	          multi_selection: false,         // 是否允许同时选择多文件
	          filters: {
	              mime_types: [               // 文件类型过滤，这里限制为图片类型
	                  {title: "Image files", extensions: "jpg,jpeg,gif,png"}
	              ]
	          },
	          auto_start: true,
	          unique_names :true,             // 自动生成文件名,如果值为false则保留原文件名上传
	          init: {
	              'FilesAdded': function (up, files) {
	                  plupload.each(files, function(file) {
	                      // 文件添加进队列后，处理相关的事情
	                  });
	              },
	              'BeforeUpload': function (up, file) {
	                  // 每个文件上传前，处理相关的事情
	              },
	              'UploadProgress': function (up, file) {
	                  // 文件上传时，处理相关的事情

	                  /*
						 * 可能是文件大小 var chunk_size =
						 * plupload.parseSize(this.getOption('chunk_size'));
						 */

	                  // 上传进度 class="layui-btn" type="button"
	                  $('#'+qiniupercent).attr('style','width:'+file.percent+'%');
	                  $("#"+qiniupercent).css("background-color","green");

	                  // console.log(file.percent + "%");
	              },
	              'UploadComplete': function () {
	                  // do something
	              },
	              'FileUploaded': function (up, file, info) {
	                  // 每个文件上传成功后,处理相关的事情
	                  // 其中 info 是文件上传成功后，服务端返回的json，形式如
	                  // {
	                  // "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
	                  // "key": "gogopher.jpg"
	                  // }
	                  var domain = up.getOption('domain');
	                  var res = eval('(' + info.response + ')'); 
	                  var sourceLink = domain + res.key;// 获取上传文件的链接地址
	                // $('#'+uploader +'
					// [name="input_qiniu_url"]').val(sourceLink);
	              /* alert("pickfiles::::"+pickfiles); */
	                      if("sgimg_add"==pickfiles){
	                 $('#btn-uploader [name="img"]').val(sourceLink);
	                 $('#btn-uploader [name="img"]').attr('src',sourceLink);
	                 $('#btn-uploader [name="cutImg"]').val(sourceLink);
	                 $('#btn-uploader [name="cutImg"]').attr('src',sourceLink);
	                    }else if("sgDetail_add"==pickfiles){
	                  	  var isNext = true;
	                  	  $("img[name='imgUrl']").each(function(i){
	                  		  if(isNext==true){
	                  		 if($(this).attr("src")==null || $(this).attr("src")=="undefined"){
	                  		  $(this).val(sourceLink);
	                           $(this).attr('src',sourceLink);
	                            isNext=false;
	                            if(i==4){
		 	                  		   $("#sgDetail_add").prop("disabled",true)
		 	                  	   }
	                  		 }
	                  		  }
	                  	  })
	                  	  
	                  	 if(isNext){
	                  		   if( $("img[name='imgUrl']").length==5)
	                  		   $("#sgDetail_add").prop("disabled",true)
	                  	   }
	                    }
	              /*
					 * $('#btn-uploader [
					 * type="button"]').css('background',"url("+sourceLink+")");
					 * $('#btn-uploader [
					 * type="button"]').css('background-size',"100%");
					 */
	                
	                  console.log(sourceLink);
	                  if(url!=null&&url!=''){
	      				$.ajax({
	      					url : url,
	      					type : 'put',
	      					dataType : 'json',
	      					contentType:"application/json; charset=utf-8",
	      					data : JSON.stringify(sourceLink),
	      				}).done(function(data) {
	      					if (data.status === '1') {
	      						   alert('上传成功！', function(){
	      							   /*
										 * table.DataTable().ajax.reload(); //
										 * 刷新table
										 * $('#modal_new_role').modal('hide');
										 */
	      			                });
	      						
	      					} else if (data.status === '2') {
	      					// $('#modal_new_role .help-block').html(data.msg);
							// // 返回错误信息
	      					}
	      				});
	      			}
	              },
	              'Error': function (up, err, errTip) {
	              	if('文件验证失败。请稍后重试。'==errTip){
	              		errTip="请上传图片格式";
	              	}
	                  alert(errTip);
	              },
	              'Key': function (up, file) {
	                  // 当save_key和unique_names设为false时，该方法将被调用
	                  var key = "";
	                  $.ajax({
	                      url: '/qiniu-token/get-key/',
	                      type: 'GET',
	                      async: false,// 这里应设置为同步的方式
	                      success: function (data) {
	                          var ext = Qiniu.getFileExtension(file.name);
	                          key = data + '.' + ext;
	                      },
	                      cache: false
	                  });
	                  return key;
	              }
	          }
	      });
	      uploader.start(); 
	  }


	  	/*
		 * 页面加载完毕 发起请求获取七牛token，通过前台传到七牛
		 */
	  	function getTokenMessageForUditor() {
	  		var url="";
	  		var qiniupercent="";
	  		var uploader="btn-uploader1";
	  		var pickfiles="pickfiles1";
	  		$.ajax({
	  			url: '/a/qiniu/uptoken',
	  			type: 'POST',
	  			data: {},
	  			cache: false,
	  			contentType: false,    // 不可缺
	  			processData: false,    // 不可缺
	  			dataType : 'json',
	  			success: function (data) {
	  				var obj = data;
	  				uploaderReadyForUditor(obj.uptoken,url,qiniupercent,uploader,pickfiles);
	  			  }
	  			});
	  	};
	     
	     function uploaderReadyForUditor(token,url,qiniupercent,uploader,pickfiles){
	      var uploaderForUditor = Qiniu.uploader({
	          runtimes: 'html5,flash,html4',
	          browse_button: pickfiles,     // 上传按钮的ID
	          container: uploader,      // 上传按钮的上级元素ID
	          drop_element: uploader,
	          max_file_size: '100mb',         // 最大文件限制
	          flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
	          dragdrop: false,
	          chunk_size: '4mb',              // 分块大小
	          // uptoken_url: '', //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
	          uptoken: token,                 // 若未指定uptoken_url,则必须指定 uptoken
												// ,uptoken由其他程序生成
	          // save_key: true, // 默认 false。若在服务端生成uptoken的上传策略中指定了
				// `sava_key`，则开启，SDK在前端将不对key进行任何处理
	          domain: qiniuConfig.returnUrl(),   // 自己的七牛云存储空间域名
	          multi_selection: true,         // 是否允许同时选择多文件
	          filters: {
	              mime_types: [               // 文件类型过滤，这里限制为图片类型
	                  {title: "Image files", extensions: "jpg,jpeg,gif,png"}
	              ]
	          },
	          auto_start: true,
	          unique_names :true,             // 自动生成文件名,如果值为false则保留原文件名上传
	          init: {
	              'FilesAdded': function (up, files) {
	                  plupload.each(files, function(file) {
	                      // 文件添加进队列后，处理相关的事情
	                  });
	              },
	              'BeforeUpload': function (up, file) {
	                  // 每个文件上传前，处理相关的事情
	              },
	              'UploadProgress': function (up, file) {
	                  // 文件上传时，处理相关的事情

	                  /*
						 * 可能是文件大小 var chunk_size =
						 * plupload.parseSize(this.getOption('chunk_size'));
						 */

	                  // 上传进度 class="layui-btn" type="button"
	                  $('#'+qiniupercent).attr('style','width:'+file.percent+'%');
	                  $("#"+qiniupercent).css("background-color","green");

	                  // console.log(file.percent + "%");
	              },
	              'UploadComplete': function () {
	                  // do something
	              },
	              'FileUploaded': function (up, file, info) {
	                  // 每个文件上传成功后,处理相关的事情
	                  // 其中 info 是文件上传成功后，服务端返回的json，形式如
	                  // {
	                  // "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
	                  // "key": "gogopher.jpg"
	                  // }
	                  var domain = up.getOption('domain');
	                  var res = eval('(' + info.response + ')'); 
	                  var sourceLink = domain + res.key;// 获取上传文件的链接地址
	              
	                 var $item = $("<div class='edui-image-item'><div class='edui-image-close'></div></div>").append($("<img src='" + sourceLink + "' class='edui-image-pic edui-image-width img-responsive' />"));

// $("#container").append($item);
	              /*
					 * var um = UM.getEditor('container');
					 * UM..execCommand('inserthtml', $item);
					 */
	                 UM.getEditor('container').focus();  
	                 UM.getEditor('container').execCommand('inserthtml',"<img src='" + sourceLink + "' class='edui-image-pic edui-image-width img-responsive' style='width:100%;'/>");  
	                  console.log(sourceLink);
	              
	              },
	              'Error': function (up, err, errTip) {
	                  alert(errTip);
	              },
	              'Key': function (up, file) {
	                  // 当save_key和unique_names设为false时，该方法将被调用
	                  var key = "";
	                  $.ajax({
	                      url: '/qiniu-token/get-key/',
	                      type: 'GET',
	                      async: false,// 这里应设置为同步的方式
	                      success: function (data) {
	                          var ext = Qiniu.getFileExtension(file.name);
	                          key = data + '.' + ext;
	                      },
	                      cache: false
	                  });
	                  return key;
	              }
	          }
	      });
	      uploaderForUditor.start(); 
	  }
	  